import Message from 'tdesign-miniprogram/message/index';

const { convertCloudUrlAsync } = require('../../utils/util');
const { processArrayImageUrls } = require('../../utils/image-processor');

// 获取应用实例
// const app = getApp()

Page({
  data: {
    swiperList: [],
    cardInfo: [],
    filterTags: [
      { id: 'hot', name: '🔥 热门', checked: true },
      { id: 'new', name: '✨ 最新', checked: false },
      { id: 'video', name: '📹 视频', checked: false },
      { id: 'ai', name: '🤖 AI', checked: false },
      { id: 'creative', name: '🎨 创意', checked: false }
    ],
    focusCardInfo: [

      {
        url: '/static/home/card1.png',
        desc: '彩色竖屏动画',
        type: 'animation',
        pageRoute: 'animation-2',
        tags: [
          {
            text: '动画',
            theme: 'primary',
          },
          {
            text: '彩色风格',
            theme: 'success',
          },
        ],
      },
    ],
    humanCardInfo: [],


    // 发布
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
  },
  // 生命周期
  onShow() {
    // 设置tab-bar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        value: 'home'
      });
    }
  },


  async onReady() {
    try {
      // 导入mock数据和helper函数
      const getHomeCards = require('../../mock/home/getHomeCards').default;
      const getHomeSwipers = require('../../mock/home/getHomeSwipers').default;
      
      const [cardData, humanCardData,swiperData, processedFocusCardInfo] = await Promise.all([
        // 使用新的异步函数获取带签名的图片URL
        getHomeCards.getCardsWithTempUrls(),
        getHomeCards.getHumanCardsWithTempUrls(), // 新增humanCardData
        getHomeSwipers.getSwipersWithTempUrls(),
        
        // 处理热门款式的图片URL
        processArrayImageUrls(this.data.focusCardInfo, ['url'], true)
      ]);
      
      console.log('cardData with temp URLs:', cardData);
      console.log('humanCardData with temp URLs:', humanCardData);
      console.log('swiperData with temp URLs:', swiperData);
      console.log('processedFocusCardInfo with temp URLs:', processedFocusCardInfo);

      this.setData({
        cardInfo: cardData,
        humanCardInfo: humanCardData, // 设置humanCardInfo
        swiperList: swiperData,
        focusCardInfo: processedFocusCardInfo,
      });
    } catch (error) {
      console.error('Failed to fetch home data:', error);
      this.setData({
        cardInfo: [],
        humanCardInfo: [], // 错误时也设置空数组
        swiperList: [],
      });
    }
  },
  onLoad(option) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true,
      });
    }
    if (option.oper) {
      let content = '';
      if (option.oper === 'release') {
        content = '发布成功';
      } else if (option.oper === 'save') {
        content = '保存成功';
      }
      this.showOperMsg(content);
    }
  },
  onPullDownRefresh() {
    this.refresh();
  },
  async refresh() {
    try {
      // 使用与初始加载相同的方法获取数据
      const getHomeCards = require('../../mock/home/getHomeCards').default;
      const getHomeSwipers = require('../../mock/home/getHomeSwipers').default;
      
      const [cardData, humanCardData, swiperData, processedFocusCardInfo] = await Promise.all([
        getHomeCards.getCardsWithTempUrls(),
        getHomeCards.getHumanCardsWithTempUrls(), // 新增humanCardData
        getHomeSwipers.getSwipersWithTempUrls(),
        processArrayImageUrls(this.data.focusCardInfo, ['url'], true)
      ]);
      
      console.log('刷新后的cardData with temp URLs:', cardData);
      console.log('刷新后的humanCardData with temp URLs:', humanCardData);
      console.log('刷新后的swiperData with temp URLs:', swiperData);
      console.log('刷新后的processedFocusCardInfo with temp URLs:', processedFocusCardInfo);

      setTimeout(() => {
        this.setData({
          cardInfo: cardData,
          swiperList: swiperData,
          humanCardInfo: humanCardData, // 设置humanCardInfo
          focusCardInfo: processedFocusCardInfo,
        });
        wx.stopPullDownRefresh();
      }, 1500);
    } catch (error) {
      console.error('Failed to refresh home data:', error);
      setTimeout(() => {
        this.setData({
          cardInfo: [],
          humanCardInfo: [], // 错误时也设置空数组
          swiperList: [],
        });
        wx.stopPullDownRefresh();
      }, 1500);
    }
  },
  showOperMsg(content) {
    Message.success({
      context: this,
      offset: [120, 32],
      duration: 4000,
      content,
    });
  },
  goRelease() {
    wx.navigateTo({
      url: '/pages/release/index',
    });
  },

  onCardTap(e) {
    const card = e.detail;  // e.detail 就是 triggerEvent 传出来的数据
    console.log('点击了卡片', card);
  
    // 使用卡片的pageRoute字段，如果没有则使用默认页面
    const pageRoute = card.pageRoute || 'task-submit';
    
    // 构造完整的页面地址
    const fullPageUrl = `/packageTask/pages/${pageRoute}/index?type=${card.type}`;
    
    console.log('跳转到页面:', pageRoute);
    console.log('完整页面地址:', fullPageUrl);
    console.log('页面参数 - type:', card.type);
    
    // 跳转到对应的任务提交页面
    wx.navigateTo({ 
      url: fullPageUrl
    });
  },

  onSwiperTap(e) {
    console.log('点击了轮播图', e.detail);
    const { index } = e.detail;
    const swiperItem = this.data.swiperList[index];
    
    if (swiperItem) {
      console.log('轮播图项目:', swiperItem);
      
      // 根据轮播图的type确定任务类型，如果没有type则根据描述判断
      let taskType = swiperItem.type || 'common';
      if (!swiperItem.type) {
        if (swiperItem.desc && swiperItem.desc.includes('数字人')) {
          taskType = 'digital-human';
        } else if (swiperItem.desc && swiperItem.desc.includes('动画')) {
          taskType = 'animation';
        } else if (swiperItem.desc && swiperItem.desc.includes('商业')) {
          taskType = 'commercial';
        } else if (swiperItem.desc && swiperItem.desc.includes('教育')) {
          taskType = 'education';
        }
      }
      
      // 跳转到任务提交页面
      wx.navigateTo({ 
        url: `/packageTask/pages/task-submit/index?type=${taskType}` 
      });
    }
  },

  /**
   * 处理筛选标签选择
   * @param {Object} e 事件对象
   */
  onFilterChange(e) {
    const { id } = e.currentTarget.dataset;
    const { checked } = e.detail;
    const { filterTags } = this.data;
    
    // 更新筛选标签状态
    const newFilterTags = filterTags.map(tag => {
      if (tag.id === id) {
        return { ...tag, checked };
      }
      return tag;
    });
    
    this.setData({ filterTags: newFilterTags });
    
    // 根据选中的标签进行内容筛选
    this.filterContent();
  },

  /**
   * 根据筛选标签过滤内容
   */
  filterContent() {
    const { filterTags } = this.data;
    const selectedTags = filterTags.filter(tag => tag.checked).map(tag => tag.id);
    
    console.log('选中的筛选标签:', selectedTags);
    
    // 这里可以根据选中的标签重新获取或筛选卡片数据
    // 例如：调用不同的API接口或者从本地数据中筛选
    if (selectedTags.includes('hot')) {
      console.log('显示热门内容');
    }
    if (selectedTags.includes('new')) {
      console.log('显示最新内容');
    }
    if (selectedTags.includes('video')) {
      console.log('显示视频内容');
    }
    // ... 其他筛选逻辑
  }
});